from sqlalchemy import Column, String, DECIMAL
from sqlalchemy.dialects.mysql import TINYINT
from itsdangerous import BadSignature, SignatureExpired
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from pydantic import BaseModel
from server.model import BaseOrm
from os import getenv
from server import db


class AppUserStatus:
    Not = 0
    Open = 1
    Close = 2
    Settled = 3


class AppUserCreate(BaseModel):
    open_id: str


class AppUserSchema(AppUserCreate):
    id: int

    class Config:
        orm_mode = True


# app用户
class AppUser(BaseOrm):
    __tablename__ = 'app_user'
    open_id = Column(String(127), nullable=False, server_default="", index=True, comment="微信id")
    balance = Column(DECIMAL(11, 2), server_default="0", nullable=False, comment="余额")
    phone = Column(String(16), index=True, nullable=False, server_default="", comment="手机号码")
    nick_name = Column(String(127), nullable=False, server_default="", comment="微信昵称")
    status = Column(TINYINT(unsigned=True), nullable=False, server_default="1", comment="状态:0:禁用, 1:正常")
    session_key = Column(String(255), nullable=False, server_default="",  comment="session_key")
    head_url = Column(String(255), comment="头像地址")

    def generate_auth_token(self, expiration=60 * 60 * 200):
        s = Serializer(getenv('SECRET_KEY'), expires_in=expiration)
        return s.dumps({'id': self.id})

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(getenv('SECRET_KEY'))
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None  # valid token, but expired
        except BadSignature:
            return None  # invalid token
        user = AppUser.query.get(data['id'])
        if not user:
            return None
        return user


db.create_all()
